<template>
  <div class="container">
    <el-dialog
      title="新增目录"
      :visible="showDialog"
      @close="close"
      width="25%"
    >
      <el-form ref="formData" :model="formData" :rules="rules">
        <el-form-item v-if="!subjectID" label="所属学科" prop="subjectName">
          <el-select v-model="formData.subjectID">
            <el-option
            v-for="obj in subjectList"
            :key='obj.value'
            :label="obj.label"
            :value="obj.value"
            >{{obj.label}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="tagName">
          <el-input v-model="formData.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button @click="addTags" type="primary">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { add, detail, update } from '@/api/hmmm/tags'
export default {
  props: {
    subjectID: {
      type: String,
      default: ''
    },
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      formData: {
        subjectID: '',
        tagName: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请输入学科名称', trigger: 'blur' }],
        tagName: [{ required: true, message: '请输入学科名称', trigger: 'blur' }]
      },
      subjectList: []
    }
  },
  created () {
    this.getSubject()
  },
  methods: {
    close () {
      this.$emit('close')
      this.formData = {
        subjectID: '',
        tagName: ''
      }
    },
    addTags () {
      this.$refs.formData.validate(async (isOk) => {
        if (isOk) {
          if (this.formData.id) {
            await update(this.formData)
            this.$message.success('更新标签成功')
          } else {
            if (this.subjectID) {
              this.formData.subjectID = Number(this.subjectID)
            }
            await add(this.formData)
            this.$message.success('添加标签成功')
          }
          this.close()
          this.$emit('update')
          this.formData = {
            subjectID: '',
            tagName: ''
          }
        }
      })
    },
    // 学科下拉
    async getSubject () {
      const res = await simple()
      this.subjectList = res.data
    },
    // 弹框内容
    async getEditTag (data) {
      const res = await detail(data)
      this.formData = res.data
    }
  }
}
</script>

<style scoped lang='less'></style>
